//
//  ChatCell.m
//  GolfFriend
//
//  Created by Vescky on 14-2-17.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "ChatCell.h"
#import "JSON.h"
#import "UserSession.h"
#import "UIImageView+MJWebCache.h"
#import <QuartzCore/QuartzCore.h>
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"

#define IMG_FACE_PREFIX @"["
#define IMG_FACE_SUFFIX @"]"
#define LABEL_TEXT_COLOR [UIColor blackColor]

@interface ChatCell () {
    NSString *avatarLink;
    UIImageView *imgvContent;
}

@end

@implementation ChatCell

#pragma mark - Public
- (void)setDataInfo:(NSDictionary*)_dict {
    float margin = 3;
    avatarLink = [_dict objectForKey:@"avatar"];
    if ([[_dict objectForKey:@"isSelf"] boolValue]) {
        avatarLink = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"avatar"];
    }
    UIView *cView = [self bubbleView:[_dict objectForKey:@"content"] from:[[_dict objectForKey:@"isSelf"] boolValue] msgType:[_dict objectForKey:@"type"]];
    [cView setFrame:CGRectMake(cView.frame.origin.x, cView.frame.origin.y + margin, cView.frame.size.width, cView.frame.size.height)];
    [self.contentView addSubview:cView];
    [self setFrame:CGRectMake(0, 0, self.frame.size.width, cView.frame.size.height + 2 * margin)];
    
}


- (float)getCellFrameHeight:(NSDictionary*)_dict {
    [self setDataInfo:_dict];
    return self.frame.size.height;
}

#pragma mark - Private
- (UIImage*)getBundleImage:(NSString*)imgName {
    imgName = [imgName stringByReplacingOccurrencesOfString:IMG_FACE_PREFIX withString:@""];
    imgName = [imgName stringByReplacingOccurrencesOfString:IMG_FACE_SUFFIX withString:@""];
    NSString *imgBundlePath = [NSString stringWithFormat:@"%@/faces.bundle",[[NSBundle mainBundle] bundlePath]];
    UIImage *image = [UIImage imageWithContentsOfFile:[imgBundlePath stringByAppendingPathComponent:imgName]];
    return image;
}

- (UIImage*)getDocumentImage:(NSString*)imgName {
    imgName = [imgName stringByReplacingOccurrencesOfString:@"GF-Document:" withString:@""];
    UIImage *img = [UIImage imageWithContentsOfFile:imgName];
    return img;
}


#pragma mark - 图文排版
/*
 生成泡泡UIView
 */
#pragma mark -
#pragma mark Table view methods
- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf msgType:(NSString*)msgType {
	// build single chat bubble cell with given text
    UIView *contentView =  [self assembleMessageAtIndex:text from:fromSelf msgType:msgType];
    contentView.backgroundColor = [UIColor clearColor];
//    CGRect cRect = contentView.frame;
//    cRect.origin.y = cRect.origin.y + 10;
//    contentView.frame = cRect;
    
    UIView *cellView = [[UIView alloc] initWithFrame:CGRectZero];
    cellView.backgroundColor = [UIColor clearColor];
    
	UIImage *bubble = [UIImage imageNamed:fromSelf?@"chat_12.png":@"chat_16.png" ];//@"chat_12.png":@"chat_16.png"
	UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:(fromSelf ? 5 : bubble.size.width - 5) topCapHeight:bubble.size.height - 5]];
    
    UIImageView *avatarImageView = [[UIImageView alloc] init];
//    [avatarImageView setImage:fromSelf ? [UIImage imageNamed:@"chat_23.png"] : [UIImage imageNamed:@"default_avatar.png"]];
    [avatarImageView setImageURLStr:avatarLink placeholder:Default_Avatar];
    
    float avatarHw = 50.0f;
    float margin = 10.0f;
    
    if(fromSelf){
        cellView.frame = CGRectMake(0, 0, contentView.frame.size.width + avatarHw + 6.5 * margin,contentView.frame.size.height + 6.5 * margin);
        cellView.frame = CGRectMake(self.frame.size.width - cellView.frame.size.width, cellView.frame.origin.y, cellView.frame.size.width, cellView.frame.size.height);
        
        bubbleImageView.frame = CGRectMake(margin, margin + 20, contentView.frame.size.width + 4 * margin, contentView.frame.size.height + 4 * margin);
        contentView.frame = CGRectMake(2 * margin,2 * margin + 20, contentView.frame.size.width, contentView.frame.size.height);
        
        if (cellView.frame.size.height < avatarHw + 2 * margin) {
            cellView.frame = CGRectMake(cellView.frame.origin.x, cellView.frame.origin.y, cellView.frame.size.width, avatarHw + 2 * margin);
        }
        
        avatarImageView.frame = CGRectMake(bubbleImageView.frame.size.width + 2 * margin, margin, avatarHw, avatarHw);
        if ([msgType isEqualToString:Message_Type_Pic]) {
           contentView.frame = CGRectMake(2.5 * margin,2.5 * margin, contentView.frame.size.width, contentView.frame.size.height);
        }
    }
	else{
        bubbleImageView.frame = CGRectMake(avatarHw + 2 * margin, margin + 20, contentView.frame.size.width + 4.5 * margin, contentView.frame.size.height + 4.5 * margin);
        contentView.frame = CGRectMake(avatarHw + 4.5 * margin, 2 * margin + 20, contentView.frame.size.width, contentView.frame.size.height);
        cellView.frame = CGRectMake(0, 0, bubbleImageView.frame.size.width + avatarHw + 3 * margin,(bubbleImageView.frame.size.height >=avatarHw ? bubbleImageView.frame.size.height : avatarHw) + 2 * margin);
        
        avatarImageView.frame = CGRectMake(margin, margin, avatarHw, avatarHw);
        if ([msgType isEqualToString:Message_Type_Pic]) {
             contentView.frame = CGRectMake(avatarHw + 5 * margin, 3 * margin, contentView.frame.size.width, contentView.frame.size.height);
        }
    }
    
    avatarImageView.layer.cornerRadius = avatarImageView.frame.size.width / 2.0;
    [avatarImageView setClipsToBounds:YES];
    
    [cellView addSubview:bubbleImageView];
    [cellView addSubview:avatarImageView];
    [cellView addSubview:contentView];
    
	return cellView;
    
}

//图文混排
-(void)getImageRange:(NSString*)message : (NSMutableArray*)array {
    NSRange range=[message rangeOfString: IMG_FACE_PREFIX];
    NSRange range1=[message rangeOfString: IMG_FACE_SUFFIX];
    //判断当前字符串是否还有表情的标志。
    if (range.length>0 && range1.length>0) {
        if (range.location > 0) {
            [array addObject:[message substringToIndex:range.location]];
            [array addObject:[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)]];
            NSString *str=[message substringFromIndex:range1.location+1];
            [self getImageRange:str :array];
        }else {
            NSString *nextstr=[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)];
            //排除文字是“”的
            if (![nextstr isEqualToString:@""]) {
                [array addObject:nextstr];
                NSString *str=[message substringFromIndex:range1.location+1];
                [self getImageRange:str :array];
            }else {
                return;
            }
        }
        
    } else if (message != nil) {
        [array addObject:message];
    }
}

#define KFacialSizeWidth  25
#define KFacialSizeHeight 25
#define MAX_WIDTH 150
-(UIView *)assembleMessageAtIndex : (NSString *) message from:(BOOL)fromself msgType:(NSString*)msgType {
    if (!msgType || msgType.length <= 0) {
        msgType = Message_Type_Txt;
    }
    //图片模式
    if ([msgType isEqualToString:Message_Type_Pic]) {
        UIView *returnView = [[UIView alloc] init];
//        UIImageView *imgView = [[UIImageView alloc] init];
        if (!imgvContent) {
            imgvContent = [[UIImageView alloc] init];
            [imgvContent setUserInteractionEnabled:YES];
            [imgvContent addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImagePre:)]];
        }
        UIImage *img = [self getDocumentImage:message];
        if (img) {
            //本地图片
            [imgvContent setImage:img];
            float imgW = img.size.width,imgH = img.size.height;

            if (img.size.width > MAX_WIDTH) {
                imgW = MAX_WIDTH;
                imgH = imgW * img.size.height / img.size.width;
            }
           
            imgvContent.frame = CGRectMake(0, 20, imgW, imgH);
        }
        else {
            //网络图片
            [imgvContent setImageURLStr:message placeholder:Default_Image_Normal];
            imgvContent.frame = CGRectMake(0, 20, 100, 100);
            imgvContent.contentMode = UIViewContentModeScaleAspectFill;
        }
        
        [imgvContent setClipsToBounds:YES];
        returnView.frame = CGRectMake(0, 0, imgvContent.frame.size.width, imgvContent.frame.size.height);
        [returnView addSubview:imgvContent];
        return returnView;
    }
    
    //文字模式
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [self getImageRange:message :array];
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    NSArray *data = array;
    UIFont *fon = [UIFont systemFontOfSize:15.0f];
    CGFloat upX = 0;
    CGFloat upY = 5;
    CGFloat X = 0;
    CGFloat Y = 0;
    if (data) {
        for (int i=0;i < [data count];i++) {
            NSString *str=[data objectAtIndex:i];
            
            if ([str hasPrefix: IMG_FACE_PREFIX] && [str hasSuffix: IMG_FACE_SUFFIX])
            {
                NSString *imageName=[str substringWithRange:NSMakeRange(1, str.length - 2)];
                UIImage *fImage = [self getBundleImage:[imageName stringByAppendingPathExtension:@"png"]];
                if (!fImage) {
                    continue;
                }
                if (upX >= MAX_WIDTH)
                {
                    upY = upY + KFacialSizeHeight;
                    upX = 0;
                    X = MAX_WIDTH;
                    Y = upY;
                }
                UIImageView *img=[[UIImageView alloc]initWithImage:fImage];
                img.frame = CGRectMake(upX, upY, KFacialSizeWidth, KFacialSizeHeight);
                [returnView addSubview:img];
                upX=KFacialSizeWidth+upX;
                if (X<MAX_WIDTH) {
                    X = upX;
                }
            } else {
                for (int j = 0; j < [str length]; j++) {
                    NSString *temp = [str substringWithRange:NSMakeRange(j, 1)];
                    if (upX >= MAX_WIDTH)
                    {
                        upY = upY + KFacialSizeHeight;
                        upX = 0;
                        X = MAX_WIDTH;
                        Y =upY;
                    }
                    CGSize size=[temp sizeWithFont:fon constrainedToSize:CGSizeMake(MAX_WIDTH, 20)];
                    UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(upX,upY,size.width,size.height)];
                    [la setTextColor:LABEL_TEXT_COLOR];
                    la.font = fon;
                    la.text = temp;
                    la.lineBreakMode = UILineBreakModeCharacterWrap;
                    la.backgroundColor = [UIColor clearColor];
                    [returnView addSubview:la];
                    upX=upX+size.width;
                    if (X<MAX_WIDTH) {
                        X = upX;
                    }
                }
            }
        }
    }
    returnView.frame = CGRectMake(0.0f,0.0f, X, Y <= 0 ? 10 : Y); //@ 需要将该view的尺寸记下，方便以后使用
    NSLog(@"%.1f %.1f", X, Y);
    return returnView;
}

#pragma mark - 放大图片
- (void)tapImagePre:(UITapGestureRecognizer *)tap
{
    // 1.封装图片数据
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:1];
    
    // 替换为中等尺寸图片
//    NSString *url = [imgArr[i] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    MJPhoto *photo = [[MJPhoto alloc] init];
    photo.url = nil; // 图片路径
    photo.srcImageView = imgvContent; // 来源于哪个UIImageView
    [photos addObject:photo];
    
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = tap.view.tag; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}


@end
